package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {


    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioProperties properties;
    @Override
    public String upload(MultipartFile file) {

        try {
            //1.创建bucket
            makeBucket();

            //2.获取文件上传名称
            String fileName = getFileName(file);

            //3.上传文件
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(properties.getBucketName())
                    .object(fileName)
                    .stream(file.getInputStream(),file.getSize(),-1)
                    .contentType(file.getContentType())
                    .build();
            minioClient.putObject(putObjectArgs);

            //4.返回url地址
            return String.join("/", properties.getEndpoint(),properties.getBucketName(),fileName);
        }catch(Exception e){
            e.printStackTrace();
            throw new IllegalArgumentException("参数异常");
        }
    }

    public String getFileName(MultipartFile file){
        String datePath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
        String uuid = UUID.randomUUID().toString();
        String fileName = file.getOriginalFilename();
        return datePath + "/" + uuid + fileName;
    }

    //校验bucket是否存在
    public void makeBucket() throws Exception{
        BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder()
                .bucket(properties.getBucketName()).build();
        Boolean flag = minioClient.bucketExists(bucketExistsArgs);
        if(!flag){
            //如果不存在 则创建bucket
            MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder().bucket(properties.getBucketName()).build();
            minioClient.makeBucket(makeBucketArgs);

            //添加权限配置文件
            SetBucketPolicyArgs policyArgs = SetBucketPolicyArgs.builder()
                    .bucket(properties.getBucketName())
                    .config(getConfig()).build();
            minioClient.setBucketPolicy(policyArgs);
        }
    }

    private String getConfig() {

        return """
            {
              "Statement" : [ {
                "Action" : "s3:GetObject",
                "Effect" : "Allow",
                "Principal" : "*",
                "Resource" : "arn:aws:s3:::%s/*"
              } ],
              "Version" : "2012-10-17"
            }
            """.formatted(properties.getBucketName());
    }

}
